import pymysql
from Scripts.headers import config, log_format
import logging


class MysqlConn:
    def __init__(self):
        logging.basicConfig(level=logging.WARNING, format=log_format)
        self.db = pymysql.connect(host=config.get('mysql', 'ip'),
                                  user=config.get('mysql', 'user'),
                                  password=config.get('mysql', 'password'),
                                  db=config.get('mysql', 'db'),
                                  port=int(config.get('mysql', 'port')))
        self.cursor = self.db.cursor()

    def insert(self, user_json):
        self.cursor.execute("INSERT INTO n_name (NAME, N_NAME) VALUES ('%s','%s');" % (user_json['DisplayName'],
                                                                                       user_json['en_name']))
        self.db.commit()
        self.db.close()
        return True

    def search_name(self, name):
        try:
            self.cursor.execute("select ID,NAME,N_NAME from n_name where N_NAME = '%s';" % name)
            result = self.cursor.fetchall()
            self.db.close()
            if result:
                return True
            else:
                return False
        except Exception as e:
            logging.warning(f'{e}')

